package com.loukou.lkt.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.loukou.lkt.company.service.UserService;
import com.loukou.lkt.lkt.redis.RedisService;
import com.loukou.lkt.lkt.resp.AuthInfo;


@Controller
public class AuthController extends BaseController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private RedisService redisService;

	/** 
	 * 无权限的跳转页面
	 */
	@RequestMapping(value = "/no_priv", method = RequestMethod.GET)
	public ModelAndView noPriv() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("no_priv");
		return mv;
	}

	/**
	 * 提交登录页面 成功时记录cookie 失败时留着本页面
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	@RequestMapping(value = "/main")
	public ModelAndView login(@RequestParam(value = "username", required = true, defaultValue = "") String username, 
			@RequestParam(value = "password",required = true, defaultValue = "" ) String password) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("login");

		AuthInfo authInfo = redisService.getAuthInfo(getSessionId());
		if(authInfo != null){
			mv.setViewName("main");
			return mv;
		}

		if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
			mv.addObject("tip", "用户名和密码不能为空");
		}else{
			authInfo = userService.getAuthInfo(username.trim(), password.trim());
			if(authInfo == null){
				mv.addObject("tip", "用户名或密码不正确");
			}else{
				authInfo.setSessionId(getSessionId());
				redisService.setAuthInfo(authInfo);
				mv.addObject("privileges", authInfo.getPrivileges());
				mv.setViewName("main");
			}
		}
		return mv;
	}

	/**
	 * 退出登录 需要身份验证 默认重定向到登录页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public String logout() {
		redisService.deleteAuthInfo(getSessionId());
		return  "login";
	}
}
